import {Component, OnInit} from '@angular/core';
import {GnLoginUser, GnMessageService, GnOAuth} from 'geminis-ng-core';
import {HttpClient} from '@angular/common/http';
import {Router} from '@angular/router';

@Component({
  selector: 'app-logining',
  template: ``
})
export class LoginingComponent implements OnInit {

  constructor(private oauth: GnOAuth,
              private http: HttpClient,
              private loginUser: GnLoginUser,
              private router: Router,
              private messageService: GnMessageService) {
  }

  ngOnInit(): void {
    this.oauth.getToken()
      .subscribe((resp: any) => {
        this.http.post('/api/resources/oauth/token', resp.id_token)
          .subscribe((newToken: any) => {
            sessionStorage.setItem('OAuthIdToken', resp.id_token);
            sessionStorage.setItem('Authorization', newToken.token);

            this.loginUser.isLogin = true;
            this.loginUser.username = newToken.username;
            this.loginUser.name = newToken.name;
            this.loginUser.authorities = newToken.authorities;
            this.loginUser.save();

            this.router.navigateByUrl('/');
          });
      }, error => {
        this.messageService.error('获取token错误，' + error.message);
      });
  }
}
